package com.wty.cmims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.pojo.Appointment;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.MedicalHistory;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.service.MedicalHistoryService;
import com.wty.cmims.mapper.MedicalHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author wty
* @description 针对表【medical_history】的数据库操作Service实现
* @createDate 2024-11-28 00:23:09
*/
@Service
public class MedicalHistoryServiceImpl extends ServiceImpl<MedicalHistoryMapper, MedicalHistory>
    implements MedicalHistoryService{
    @Autowired
    private MedicalHistoryMapper medicalHistoryMapper;
    @Autowired
    private AppointmentServiceImpl appointmentService;
    @Override
    public ResponseResult<Map<String, Object>> medicalHistoryFindById(Integer AppointmentId) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        // 判断是否存在此预约ID的病历
        LambdaQueryWrapper<MedicalHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MedicalHistory::getAppointmentId, AppointmentId);
        MedicalHistory medicalHistory = this.getOne(wrapper);
        Map<String, Object> map;
        if (medicalHistory == null){
            // 如果不存在appointment_id
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("暂无该次病历");
            return responseResult;
        }else{
            // 如果存在appointment_id
            map = medicalHistoryMapper.findResidentMedicalHistoryById(AppointmentId);
        }
        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (map.get("updated_time") != null){
                map.put("updated_time", sdfDateTime.format(sdfDateTime.parse(map.get("updated_time").toString())));
            }
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("查询居民病历成功");
            responseResult.setData(map);
        } catch (Exception e) {
            System.out.println("日期转换错误");
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("查询居民病历失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> medicalHistoryUpdate(Map<String, Object> paramsMap) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy/MM/dd");
        Date date = null;
        try {
            if (paramsMap.get("visit_date") != null){
                date = sdfDay.parse(paramsMap.get("visit_date").toString());
            }
        } catch (ParseException e) {
            System.out.println("日期转换错误");
        }
        if (date != null) {
            paramsMap.put("visit_date", date);
        }
        Integer rows = medicalHistoryMapper.updateMedicalHistory(paramsMap);
        if (rows > 0) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("居民病历更新成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("居民病历更新失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> medicalHistoryAdd(Map<String, Object> paramsMap) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        // 判断预约状态是否为进行中
        LambdaQueryWrapper<Appointment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Appointment::getId, paramsMap.get("appointment_id"));
        Appointment appointment = appointmentService.getOne(wrapper);
        if (appointment.getStatus() != 2){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("请先返回确认开始问诊");
            return responseResult;
        }

        MedicalHistory medicalHistory = new MedicalHistory();
        medicalHistory.setResidentId(Integer.parseInt((String) paramsMap.get("resident_id")));
        medicalHistory.setDoctorId((Integer) paramsMap.get("doctor_id"));

        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy/MM/dd");
        Date date = null;
        try {
            if (paramsMap.get("visit_date") != null){
                date = sdfDay.parse(paramsMap.get("visit_date").toString());
            }
        } catch (ParseException e) {
            System.out.println("日期转换错误");
        }
        if (date != null) {
            paramsMap.put("visit_date", date);
        }

        medicalHistory.setVisitDate((Date) paramsMap.get("visit_date"));
        medicalHistory.setChiefComplaint((String) paramsMap.get("chief_complaint"));
        medicalHistory.setPresentIllness((String) paramsMap.get("present_illness"));
        medicalHistory.setPastMedicalHistory((String) paramsMap.get("past_medical_history"));
        medicalHistory.setPastSurgicalHistory((String) paramsMap.get("past_surgical_history"));
        medicalHistory.setDiagnosis((String) paramsMap.get("diagnosis"));
        medicalHistory.setTreatment((String) paramsMap.get("treatment"));
        medicalHistory.setNotes((String) paramsMap.get("notes"));
        medicalHistory.setUpdatedUser((Integer) paramsMap.get("update_user"));
        medicalHistory.setAppointmentId(Integer.parseInt((String) paramsMap.get("appointment_id")));
        medicalHistory.setInstitutionId((Integer) paramsMap.get("institution_id"));
        boolean save = this.save(medicalHistory);
        if (save) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("病历添加成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("病历添加失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> medicalHistoryListFindByResidentId(Map<String, Object> paramsMap) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        Integer residentId = Integer.parseInt((String) paramsMap.get("resident_id"));
        // 根据residentId查出所有appointment_id
        LambdaQueryWrapper<MedicalHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MedicalHistory::getResidentId, residentId);
        wrapper.orderByDesc(MedicalHistory::getId);
        List<MedicalHistory> medicalHistories = this.list(wrapper);
        Integer[] appointmentIds = new Integer[medicalHistories.size()];
        for (MedicalHistory medicalHistory : medicalHistories) {
            appointmentIds[medicalHistories.indexOf(medicalHistory)] = medicalHistory.getAppointmentId();
        }
        // 根据AppointmentId查出过往病历列表
        List<Map<String, Object>> list = new ArrayList<>();
        for (Integer appointmentId : appointmentIds) {
            Map<String, Object> map = this.medicalHistoryFindById(appointmentId).getData();
            if (map != null) {
                list.add(map);
            }
        }
        if (!list.isEmpty()) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("查询成功");
            responseResult.setDatas(list);
            responseResult.setTotal(list.size());
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("查询失败");
        }
        return responseResult;
    }
}